<?php

   /*
    * 版本版本上线  2016-08-04
    * 
    * */
   class  ApiCenter_ProductApi_Model_Upload_Api  extends  Mage_Catalog_Model_Api_Resource {
     
       /*
        * 版本版本上线  2016-08-04
        *
        * */
       protected  $result = array(
       
       );
        
       protected  $need_filter = array(
           "name",
           "description",
           "short_description",
       );
       protected  $res_product = array(
       
       );
       protected  $no_required = array(
           "common_reasons",//拒绝原因'字段，新增时不可见
           "pulscen",
           "common_warehouse_code",
           "price_view",
           "giftcard_amounts",
           "allow_open_amount",
           "common_weight",
           "open_amount_min",
           "open_amount_max",
           "group_price",
           "tier_price",
           "common_supply_price",
           "msrp_enabled",
           "msrp_display_actual_price_type",
           "common_supplier_special_price",
           "attr_giftcard_amounts",
           "fb_product",
           "news_from_date",
           "news_to_date",
           "url_key",
           "country_of_manufacture",
           "is_returnable",
           "em_featured",
           "em_deal",
           "em_hot",
           "yml",
           "sku",
           "vendor_id",
           "visibility",
           "status",
           //"approval",
           "cost",
           "yandex_market_product_category",
           "tax_class_id",
           "tiers_table",
           "msrp",
           "common_other_shipping_type",
           "common_publish_platform",
           "common_shipping_method",
           "common_dimensional_weight",
           "inventory_manage_stock",
           "inventory_min_sale_qty",
           "inventory_max_sale_qty",
           "inventory_is_qty_decimal",
           "inventory_notify_stock_qty",
           "inventory_enable_qty_increments",
           "inventory_backorders",
           "simple_product_visibility",
       );
       protected  $required_fields = array(
           "stock_data",
           "category"
       );
       
       private   $additional ="Additional Product Information";
       
       
       const DEFULT_VISIBILITY = "1";
        
       const DEFULT_STAUTS = "2";
        
       const DEFULT_APPROVAL = "0";
       
       const  WEBSITEID = "1";
       
       const PAGE_SIZE_DEFAULT =10;
       
       const PAGE_SIZE_MAX = 100;
       
       const  CN = 3;
        
       protected $_websites = array(
           "1",
       );
       
       
       protected $_mimeTypes = array(
           'image/jpeg' => 'jpg',
           'image/gif'  => 'gif',
           'image/png'  => 'png'
       );
       
       const ATTRIBUTE_CODE = 'media_gallery';
       
       /**
        *  Set additional data before product saved
        *
        *  @param    Mage_Catalog_Model_Product $product
        *  @param    array $productData
        *  @return   object
        */
       protected function _prepareDataForSave($product, $productData,$type)
       {
           if (isset($productData['website_ids']) && is_array($productData['website_ids'])) {
               $product->setWebsiteIds($productData['website_ids']);
           }
       
           foreach ($product->getTypeInstance(true)->getEditableAttributes($product) as $attribute) {
               //Unset data if object attribute has no value in current store
               if (Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID !== (int) $product->getStoreId()
                   && !$product->getExistsStoreValueFlag($attribute->getAttributeCode())
                   && !$attribute->isScopeGlobal()
                   ) {
                       $product->setData($attribute->getAttributeCode(), false);
                   }
       
                   if ($this->_isAllowedAttribute($attribute)) {
                       if (isset($productData[$attribute->getAttributeCode()])) {
                           $product->setData(
                               $attribute->getAttributeCode(),
                               $productData[$attribute->getAttributeCode()]
                               );
                       } elseif (isset($productData['additional_attributes']['single_data'][$attribute->getAttributeCode()])) {
                           $product->setData(
                               $attribute->getAttributeCode(),
                               $productData['additional_attributes']['single_data'][$attribute->getAttributeCode()]
                               );
                       } elseif (isset($productData['additional_attributes']['multi_data'][$attribute->getAttributeCode()])) {
                           $product->setData(
                               $attribute->getAttributeCode(),
                               $productData['additional_attributes']['   '][$attribute->getAttributeCode()]
                               );
                       }
                   }
           }
       
          if (isset($productData['category'])) {
            $allCategoryInfo = array();
            $MetaKeyword ="";
              $category_id = $productData['category'];

            
            //加载出所有父集category 返回 name url_key  
            $this->_loadAllParentCategory($category_id,$allCategoryInfo);
            if(empty($allCategoryInfo)){
                $this->_fault("category is fault!");
            }
            ksort($allCategoryInfo);
            foreach ($allCategoryInfo as $cid =>$val){
                $productData['categories'][] =$cid;
                $MetaKeyword.=$val['name'].",";
            }
            $productData['categories']= array_unique($productData['categories']);
            Mage::log($productData['categories']);
            $product->setMetaTitle("");
            $product->setMetaKeyword($MetaKeyword);
            $product->setMetaDescription("");
         
            $product->setCategoryIds($productData['categories']);
            
        }
            
           if(!isset($productData['websites'])){
               $productData['websites'] = array("1");
           }
          
           if (isset($productData['websites']) && is_array($productData['websites'])) {
               foreach ($productData['websites'] as &$website) {
                   if (is_string($website)) {
                       try {
                           $website = Mage::app()->getWebsite($website)->getId();
                       } catch (Exception $e) { }
                   }
               }
               $product->setWebsiteIds($productData['websites']);
           }
       
           if (Mage::app()->isSingleStoreMode()) {
               $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
           }
       
           if (isset($productData['stock_data']) && is_array($productData['stock_data'])) {
               $product->setStockData($productData['stock_data']);
           }
       
           if (isset($productData['tier_price']) && is_array($productData['tier_price'])) {
               $tierPrices = Mage::getModel('catalog/product_attribute_tierprice_api')
               ->prepareTierPrices($product, $productData['tier_price']);
               $product->setData(Mage_Catalog_Model_Product_Attribute_Tierprice_Api::ATTRIBUTE_CODE, $tierPrices);
           }
           //可配置商品需要传输的参数
           if ($type=='configurable'&& is_array($productData['configurable_attributes_data'])) {
               $product->setConfigurableAttributesData($productData['configurable_attributes_data']);
           }
       
           if ($type=='configurable'&& is_array($productData['configurable_products_data'])) {
               $product->setConfigurableProductsData($productData['configurable_products_data']);
           }
       
           if ($type=='configurable'&& $productData['can_save_configurable_attributes']) {
               $product->setCanSaveConfigurableAttributes(true);
           }
       }
       
    
       /**
        * Check if attributeSet is exits and in catalog_product entity group type
        *
        * @param  $attributeSetId
        * @throw Mage_Api_Exception
        * @return void
        */
       protected function _checkProductAttributeSet($attributeSetId)
       {
           $attributeSet = Mage::getModel('eav/entity_attribute_set')->load($attributeSetId);
           if (is_null($attributeSet->getId())) {
               $this->_fault('product_attribute_set_not_exists');
           }
           if (Mage::getModel('catalog/product')->getResource()->getTypeId() != $attributeSet->getEntityTypeId()) {
               $this->_fault('product_attribute_set_not_valid');
           }
       }
       /**
        * 组合可配置产品所需要的信息
        * */
       protected  function getConfigAttrCode($attributeSetId,$select=array(),$simpleProductArr){
           try {
               $AttributeCode   =array();
               $attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);
               foreach($attributes as $_attribute)
               {
                   if($_attribute['scope'] == 'global' && $_attribute['type'] == 'select')
                   {
                       $super_attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product',$_attribute['code']);
                       if($super_attribute->getIsConfigurable() == 1)
                       {
                           $AttributeCodeData[] = $super_attribute->getData();
                       }
                   }
               }
       
               $simpleProducts = Mage::getResourceModel('catalog/product_collection')
               ->addIdFilter($simpleProductArr);
       
               foreach ($select as $val){
                   $simpleProducts -> addAttributeToSelect($val);
               }
               foreach ($AttributeCodeData as  $configurableAtt){
                   foreach ($select as $attribute_code ){
                       if($configurableAtt['attribute_code'] == $attribute_code ){
                           foreach ($simpleProducts as $simple){
                               $productinfo = array(
                                   'label' => $simple->getAttributeText($configurableAtt['attribute_code']),
                                   'attribute_id' => $configurableAtt['attribute_id'],
                                   'value_index' => (int) $simple->getData($attribute_code),
                                   'is_percent' => 0,
                                   'pricing_value' => 0
                               );
                               $values[$attribute_code][]= $productinfo;
                               $configurableProductsData[$simple->getId()][] = $productinfo;
                           }
       
                           $configurableAttributesData[] = array(
                               'label'          => $configurableAtt['frontend_label'],
                               'position'       => $configurableAtt['position'],
                               'values'         => $values[$attribute_code]?$values[$attribute_code]:array(),
                               'attribute_id'   => $configurableAtt['attribute_id'],
                               'attribute_code' =>  $configurableAtt['attribute_code'],
                               'frontend_label' =>$configurableAtt['frontend_label'],
                           );
                       }
                   }
               }
               $configurableKey['configurable_attributes_data'] = $configurableAttributesData;
               $configurableKey['configurable_products_data']  = $configurableProductsData;
       
               return $configurableKey;//返回用户所绑定的属性
       
           } catch (Mage_Core_Exception $e) {
               Mage::log('DEBUG_ERROR');
               $this->_fault('system_error_contactmonkey');
           }
            
       }
       /**
        * 获取产品信息
        * */
       protected  function  _getProductInfo($product_id,$vendor){
           $qtyNum=0;
           $childprice =array();
           if (is_string($product_id) && !preg_match("/^[+-]?[1-9][0-9]*$|^0$/", $product_id)) {
               $product_id=$vendor['vendor_id']."_".$product_id;
           }
            
           $product = $this->_getProduct($product_id, $store=null, $identifierType=null);
           if($product->getVendorId()!=$vendor['entity_id']){ $this->_fault('The goods do not belong to you or no existing');}
           $stock_model=$product->getStockItem();
           $this->res_product['sku']=$product->getVendorSku();
           $this->res_product['prodcut_id']=$product->getId();
           $this->res_product['type']=$product->getTypeId();
           $this->res_product['is_in_stock']=$stock_model->getIsInStock();
           if($product->getTypeId()=="configurable"){
               $configurableProduct = Mage::getModel('catalog/product_type_configurable')->setProduct($product);
               $allSubProducts = $configurableProduct->getUsedProductCollection()
               ->addAttributeToSelect('status')
               ->addAttributeToSelect('price')
               ->addFilterByRequiredOptions();
               $subQty = array();
               foreach ($allSubProducts as $subProduct){
                 
                   $qty = intval(Mage::getModel('cataloginventory/stock_item')->loadByProduct($subProduct)->getQty());
                   $qtyNum +=$qty;
                   $subQty[$subProduct->getVendorSku()] = $qty;
                   $childprice[] = $subProduct->getPrice();
               }
               $this->res_product['price'] =round(max($childprice),2) ;
               $this->res_product['qty']=$qtyNum;
               $this->res_product['qty_details']=$subQty;     
           }else{
               $this->res_product['price']= round($product->getPrice(),2);
               $this->res_product['qty']=(int)$stock_model->getQty();
           }
           
           return $this->res_product;
       }

       protected function _checkProductTypeExists($productType)
       {
           if (!in_array($productType, array_keys(Mage::getModel('catalog/product_type')->getOptionArray()))) {
               $this->_fault('product_type_not_exists');
           }
       }
       protected function makeXmlToarr($xmlStr){
           $obj = simplexml_load_string($xmlStr);
           $resultArr['request'] =  json_decode( json_encode($obj),true);
           return  $resultArr['request'];
       }
       
       /**
        *  查询属性的选项值
        **/
       protected function getAttributesOption($attributId) {
       
           $attributeObject=Mage::getModel('eav/config')->getAttribute('catalog_product',$code="")->load($attributId);
           $options = $attributeObject->setStoreId(self::WEBSITEID)->getSource()->getAllOptions(false);
           return $options;
       }
       /**
        *  加载category的所有父集category
        * */
       
       protected  function _loadAllParentCategory($categoryid,&$ids){
       
           $_categoryData = Mage::getModel('catalog/category')->load($categoryid)->getData();
            
           $val['name'] = $_categoryData['name'];
           $val['url_key'] = $_categoryData['url_key'];
           $ids[$_categoryData['entity_id']] = $val;
           if($_categoryData['parent_id'] !="2"){
               $this->_loadAllParentCategory($_categoryData['parent_id'],$ids);
           }
       }
       /**
        *   vendor tovalidate(商家账户验证)
        *   @param $vendor_name
        *   @param $password
        *   @return  $vendor_id
        *   未进行session 控制（待解决）
        * */
       protected  function validateVendors($username,$password){
            
           /** @var $vendor VES_Vendors_Model_Vendor */
           $vendor = Mage::getModel('vendors/vendor');
           $session = Mage::getSingleton('vendors/session');
            
           $vendor->setWebsiteId(self::WEBSITEID);
       
           /*Check if login is email*/
           $validator = new Zend_Validate_EmailAddress();
           if($validator->isValid($username)) {
               $vendor->loadByEmail($username,$vendor->getWebsiteId());
           }else{
               $vendor->loadByVendorId($username,$vendor->getWebsiteId());
           }
           if (!$vendor->validatePassword($password)) {
               $this->_fault('Invalid login or password.');
           }
       
           if ($vendor->getConfirmation() && $vendor->isConfirmationRequired()) {
                
               $this->_fault('Your vendor account is not confirmed.');
           }
       
           if ($vendor->getStatus() ==$vendor::STATUS_PENDING){
               $this->_fault('Your vendor account is awaiting for approval.');
           }
       
           if ($vendor->getStatus() == $vendor::STATUS_DISABLED) {
       
               $this->_fault('Your vendor account has been suppended');
                
           }
       
           Mage::dispatchEvent('customer_customer_authenticated', array(
               'model'    => $vendor,
               'password' => $password,
           ));
       
           $session->setVendorAsLoggedIn($vendor);
       
           return $session->getVendor()->getData();
       }
       /**
        * 根据id删除产品
        * */
        protected function deleteProduct($productIds){
                
                if(!empty($productIds)){
                    try{
                        foreach ($productIds as $_productId){
                            $product = Mage::getSingleton('catalog/product')->load($_productId); 
                            $product->delete();
                        }
                    }catch(Exception $e) {
                        Mage::log("soap:子产品产品删除失败:".$_productId);
                        }
                    }
                }
                
                
                
         /**
          * 上传图片
          * 
          * @param unknown $product
          * @param unknown $data
          * @throws Mage_Core_Exception*/     
                
          protected function _getGalleryAttribute($product)
                {
                    $attributes = $product->getTypeInstance(true)
                    ->getSetAttributes($product);
                
                    if (!isset($attributes[self::ATTRIBUTE_CODE])) {
                        $this->_fault('not_media');
                    }
                
                    return $attributes[self::ATTRIBUTE_CODE];
                }
          protected function uploadImage($product,$data) {
                
                    $gallery = $this->_getGalleryAttribute($product);
                    if ( !isset($data['mime']) || !isset($data['content'])) {
                        $this->_fault('data_invalid', Mage::helper('catalog')->__('The image is not specified.'));
                    }
                
                    if (!isset($this->_mimeTypes[$data['mime']])) {
                        $this->_fault('data_invalid', Mage::helper('catalog')->__('Invalid image type.'));
                    }
                
                    $fileContent = @base64_decode(trim($data['content']), true);
                    if (!$fileContent) {
                        $this->_fault('data_invalid', Mage::helper('catalog')->__('The image contents is not valid base64 data.'));
                    }
                
                    unset($data['content']);
                
                    $tmpDirectory = Mage::getBaseDir('var') . DS . 'api' . DS . $this->_getSession()->getSessionId();
                
                    if (isset($data['name']) && $data['name']) {
                        $fileName  = $data['name'];
                    } else {
                        $fileName  = 'image';
                    }
                    $fileName .= '.' . $this->_mimeTypes[$data['mime']];
                
                    $ioAdapter = new Varien_Io_File();
                    try {
                        // Create temporary directory for api
                        $ioAdapter->checkAndCreateFolder($tmpDirectory);
                        $ioAdapter->open(array('path'=>$tmpDirectory));
                        // Write image file
                        $ioAdapter->write($fileName, $fileContent, 0777);
                        unset($fileContent);
                
                        // try to create Image object - it fails with Exception if image is not supported
                        try {
                            new Varien_Image($tmpDirectory . DS . $fileName);
                        } catch (Exception $e) {
                            // Remove temporary directory
                            $ioAdapter->rmdir($tmpDirectory, true);
                            throw new Mage_Core_Exception($e->getMessage());
                        }
                
                        // Adding image to gallery
                        $file = $gallery->getBackend()->addImage(
                            $product,
                            $tmpDirectory . DS . $fileName,
                            null,
                            true,
                            false
                        );
                        // Remove temporary directory
                        $ioAdapter->rmdir($tmpDirectory, true);
                
                
                    } catch (Mage_Core_Exception $e) {
                        $this->_fault('not_created', $e->getMessage());
                    } catch (Exception $e) {
                        $this->_fault('not_created', Mage::helper('catalog')->__('Cannot create image.'));
                    }
                    return $gallery->getBackend()->getRenamedImage($file);
                }
                /**
                 * 返回数组的维度
                 * @param  [type] $arr [description]
                 * @return [type]      [description]
                 */
                protected  function arrayLevel($arr){
                    $al = array(0);
                    $this-> aL($arr,$al);
                    return max($al);
                }
                protected  function aL($arr,&$al,$level=0){
                    if(is_array($arr)){
                        $level++;
                        $al[] = $level;
                        foreach($arr as $v){
                            $this->aL($v,$al,$level);
                        }
                    }
                }
    }